package com.example.animationplayer.page

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.widget.Toast
import com.example.animationplayer.databinding.ActivityAlphaAnimationBinding
import com.example.animationplayer.tool.Debugs
import com.example.animationplayer.tool.FileUtil
import com.example.animationplayer.tool.PermissionUtils
import com.ss.ugc.android.alpha_player.IMonitor
import com.ss.ugc.android.alpha_player.IPlayerAction
import com.ss.ugc.android.alpha_player.model.ScaleType

class AlphaAnimationActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "AlphaAnimationActivity"
        fun start(context: Context) {
            val starter = Intent(context, AlphaAnimationActivity::class.java)
            context.startActivity(starter)
        }
    }

    private val resourceDir by lazy { getExternalFilesDir(Environment.DIRECTORY_MOVIES)?.absolutePath ?: Environment.getExternalStorageDirectory().path }

    private lateinit var binding: ActivityAlphaAnimationBinding

    private val playerAction = object : IPlayerAction {
        override fun onVideoSizeChanged(videoWidth: Int, videoHeight: Int, scaleType: ScaleType) {
            Debugs.i(TAG, "onVideoSizeChanged, videoWidth = $videoWidth, videoHeight = $videoHeight, scaleType = $scaleType")
        }

        override fun startAction() {
            Debugs.i(TAG, "startAction()")
        }

        override fun endAction() {
            Debugs.i(TAG, "endAction")
        }
    }

    private val monitor = object : IMonitor {
        override fun monitor(state: Boolean, playType: String, what: Int, extra: Int, errorInfo: String) {
            Debugs.i(TAG, "monitor state: $state, playType = $playType, what = $what, extra = $extra, errorInfo = $errorInfo")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAlphaAnimationBinding.inflate(layoutInflater)
        setContentView(binding.root)

        FileUtil.copyAssetsToStorage(this, resourceDir, arrayOf("login_alpha.mp4", "config.json")) {
            runOnUiThread {
                Toast.makeText(this, "Copy file Success", Toast.LENGTH_SHORT).show()
            }
        }
        binding.vgvAlpha.initPlayerController(this, this, playerAction, monitor)

        binding.btnAttach.setOnClickListener {
            PermissionUtils.verifyStoragePermissions(this)
            binding.vgvAlpha.attachView()
        }

        binding.btnDetach.setOnClickListener {
            binding.vgvAlpha.detachView()
        }

        binding.btnStart.setOnClickListener {
            binding.vgvAlpha.startVideoGift(resourceDir)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.vgvAlpha.releasePlayerController()
    }
}